package com.cn.wanxi.util;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class MyFilter implements Filter {
    /**
     * servlet生命周期
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 过滤放行
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
/**
 * 1.判断用户是否已经登录
 * 2.如果登录就放行---可以访问后台接口
 * 3.如果没有登录，则返回登录页面
 * 重定向和页面转发？
 */
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //        乱码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        String url = req.getServletPath();
        System.out.println(url);
//        只有访问后台的连接以back开始的才需要登录
        if (url.startsWith("/back/")) {
            String loginName =req.getParameter("loginName");
            String username = (String) req.getSession().getAttribute(loginName);
            if (username == null) {
                resp.sendRedirect("/html/login.html");
            } else {
                filterChain.doFilter(req, resp);
            }
        } else {
            filterChain.doFilter(req, resp);//放行
        }

    }

    @Override
    public void destroy() {

    }
}
